import json
from frame_work.logger import Logger
from frame_work.login import AdminLogin
from frame_work.util import check_tid, assert_result_dict, get_sql_info
from frame_work import menu_list
from frame_work.setting import *
from frame_work.yaml_file import YAML

logger = Logger(__name__).get_logger()


class Rebate(object):

    def __init__(self, tid, uname=None):
        self.tid = tid
        self.uname = uname
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        self.session = self.get_session()

    def get_session(self):
        # 管理员登录session
        login = AdminLogin()
        login.admin_card_login()
        return login.get_session()

    def rebate(self):
        """
        通过报告直接无密返款
        :return:
        """
        statement = """SELECT jid from sk_join where trade_no_state =3 and report_state=2 and buyer_uname= %s and tid = %s"""
        params = (self.uname, self.tid)
        value = get_sql_info(statement, params, meta={
            "info": "查询参与jid"
        })
        try:
            jid = value[0].get("jid")
        except Exception as e:
            logger.debug("没有待审核报告，所以无法无密返款 %s" % e)
        else:
            yaml_data = self.yaml.get_data('admin_audit_report')
            yaml_data.get('data').update({
                'jid': jid
            })
            response = self.session.post(
                yaml_data.get('url'),
                data=yaml_data.get('data'),
                headers=yaml_data.get('header')).text
            assert_result_dict(response, '管理员通过报告直接无密返款')

    def rebate_all(self):
        """
        一键无密返款所有待审核报告用户，
        :return:
        """
        statement = """SELECT jid from sk_join where trade_no_state =3 and report_state=2 and tid = %s"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询所有参与jid"
        })
        jids = []
        try:
            for obj in value:
                jid = obj.get("jid")
                jids.append(jid)
        except Exception as e:
            logger.debug("没有待审核报告，所以无法无密返款 %s" % e)
        else:
            yaml_data = self.yaml.get_data('admin_audit_report')

            for index, jid in enumerate(jids, start=1):
                logger.debug('开始返款第%s个用户...' % index)
                yaml_data.get('data').update({
                    'jid': jid
                })
                response = self.session.post(
                    yaml_data.get('url'),
                    data=yaml_data.get('data'),
                    headers=yaml_data.get('header')).text
                assert_result_dict(response, '管理员通过报告jid:%s直接无密返款' % jid)


def assert_result(value, promote):
    """
    判断返款结果
    :param value:
    :param promote:
    :return:
    """
    result = json.loads(promote)['success']
    if result:
        logger.info('管理员执行无密返款成功[%s]' % value)
    else:
        data = json.loads(promote)['data']
        logger.info('管理员执行无密返款失败[%s]，失败原因：%s' % (value, data))


def main():

    while True:
        # 显示功能菜单
        menu_list.rebate_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            if choise == '1':
                buyer_uname = input('请输入您要返款的试客账户: ')
                reb = Rebate(tid, buyer_uname)
                reb.rebate()
            elif choise == '2':
                reb = Rebate(tid)
                reb.rebate_all()
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    main()
